package com.lh.project.service.impl;


import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.project.common.BaseResponse;
import com.lh.project.common.JwtUtil;
import com.lh.project.common.ResultUtils;
import com.lh.project.common.UserHolder;
import com.lh.project.model.entity.User;
import com.lh.project.model.vo.UserVO;
import com.lh.project.service.UserService;
import com.lh.project.mapper.UserMapper;
import org.apache.ibatis.annotations.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
*
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService{

    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        return 0;
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        return null;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        return false;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        return null;
    }

    @Override
    public User getByOpenid(User user) {
        User user1 = userMapper.getByOpenid(user.getOpenid());
        System.out.println("通过openId找出来的user是："+user1);
        if(user1 == null || user1.getId()==null){
            //表示这个用户数据库中还没有
            //将该用户保存到数据库中去
            save(user);
            return user;
        }else{
            //表示数据库中有该用户
            return user1;
        }
    }

    @Override
    public User bindStuNumber(Long stuNumber, HttpServletRequest httpServletRequest) {
//        String userId = httpServletRequest.getHeader("userId");
        Long userId = UserHolder.getUser().getId();
        //获取用户消息
        User user = getById(userId);
        user.setStuNumber(stuNumber);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",userId);
        update(user,queryWrapper);
        System.out.println("绑定学号之后的用户信息："+user);
        return user;
    }

    @Override
    public BaseResponse<String> login(User user){
        //先验证用户信息的正确性,如果没用该用户，创建一个
        User user1 = getByOpenid(user);
        //如果用户不存在，保存用户到数据库中
        if(user1==null){
            save(user);
            //将新创建的用户记住，主要要使用到它的id
            user1 = user;
        }
        //开始jwt
        UserVO userVO = new UserVO(user1);
        String token = JwtUtil.createJWT(userVO);
        return ResultUtils.success(token);
    }
}
